import 'package:development_assistant/config/font.dart';
import 'package:development_assistant/controller/database_controller.dart';
import 'package:development_assistant/ui/screen/widget/custom_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../config/colors.dart';

class AddDatabase extends StatelessWidget {

  AddDatabase({super.key});

  final DatabaseController databaseController=Get.put(DatabaseController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(),
      bottomNavigationBar: _saveTable(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 20.w,horizontal: 20.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _databaseField("数据库名".tr,databaseController.dbName),
                  _databaseField("数据库描述".tr,databaseController.dbDesc),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _databaseField("主机号".tr, databaseController.dbHost),
                  _databaseField("端口号".tr, databaseController.dbPort),
                ],
              ),
              _databaseField("Url".tr,databaseController.dbUrl ),
              _tableField(),
              SizedBox(height: 20.h,)
            ],
          ),
        ),
      ),
    );
  }

  _saveTable(){
    return Container(
      width: 200.w,
      height: 35.h,
      margin: EdgeInsets.symmetric(vertical: 10.h),
      padding: EdgeInsets.symmetric(horizontal: 100.w),
      child: ElevatedButton(
        onPressed: (){
          Get.defaultDialog(
            title: "保存数据库".tr,
            middleText: "${'是否保存该数据库?'.tr} : ${databaseController.dbName}",
            confirm: TextButton(
              style: TextButton.styleFrom(
                  backgroundColor: ColorsConfig().buttonColorOfTheme,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)
                  )
              ),
              onPressed: (){
                databaseController.addDatabase();
              },
              child: Text("确定".tr),
            ),
            cancel:TextButton(
              style: TextButton.styleFrom(
                  backgroundColor:  ColorsConfig().buttonColorOfTheme,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)
                  )
              ),
              onPressed: (){
                Get.back();
              },
              child:Text("取消".tr),
            ),
          );
        },
        style: ElevatedButton.styleFrom(
            backgroundColor:  ColorsConfig().buttonColorOfTheme,
            foregroundColor: Colors.white,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20)
            )
        ),
        child: Text("保存数据库".tr,style: TextStyle(fontWeight: FontWeight.bold),),
      ),
    );
  }

  _databaseField(String hintText,RxString dbValue){
    return Container(
      width: hintText=="Url"?320.w:155.w,
      height: 50.h,
      margin: EdgeInsets.symmetric(vertical: 5.h),
      child: Center(
        child: TextField(
          maxLines: 1,
          decoration: InputDecoration(
              hintText:hintText,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(15),
              )
          ),
          onChanged: (e){
            dbValue.value=e;
          },
        ),
      ),
    );
  }

  _tableField(){
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            CustomText(text: "数据表".tr, textStyle: FontConfig.titleStyle),
            ElevatedButton.icon(
              onPressed: (){
                databaseController.tableList.add({
                  "table_id":null,
                  "db_id":0,
                  "table_name":"",
                  "table_sort":"",
                  "table_engine":""
                });

                databaseController.columnList.add([
                  {
                    "column_id":null,
                    "table_id":0,
                    "column_name":"",
                    "column_type":"",
                    "column_kind":""
                  }
                ].obs);
              },
              icon: const Icon(Icons.create),
              label: Text("创建".tr),
              style: ElevatedButton.styleFrom(
                  backgroundColor:  ColorsConfig().buttonColorOfTheme,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)
                  )
              ),
            ),
          ],
        ),
        Obx(() => Wrap(
         children: List<Widget>.generate(databaseController.tableList.length, (index) {
           return Container(
             margin: EdgeInsets.only(bottom: 10.h),
             padding: EdgeInsets.symmetric(horizontal: 10.w),
             decoration: BoxDecoration(
                 borderRadius: BorderRadius.circular(10),
                 border: Border.all(color:Colors.grey,width: 1)
             ),
             child: Column(
               crossAxisAlignment: CrossAxisAlignment.start,
               children: [
                 //Table信息
                 Row(
                   children: [
                     Container(
                       margin: EdgeInsets.only(right: 20.w),
                       width: 100.w,
                       child: TextField(
                         decoration:InputDecoration(
                             hintText: "数据表名".tr,
                         ),
                         onChanged: (e){
                           databaseController.tableList[index]['table_name']=e;
                         },
                       ),
                     ),
                     SizedBox(
                       width: 125.w,
                       child: TextField(
                         decoration: InputDecoration(
                             hintText: "排序方法".tr,
                         ),
                         onChanged: (e){
                           databaseController.tableList[index]['table_sort']=e;
                         },
                       ),
                     ),
                     IconButton(
                         onPressed: (){
                           databaseController.tableList.removeAt(index);
                           databaseController.columnList.removeAt(index);
                         },
                         icon: Icon(Icons.delete_outline)
                     )
                   ],
                 ),
                 SizedBox(
                   width: 245.w,
                   child: TextField(
                     decoration:InputDecoration(
                       hintText: "引擎".tr,
                     ),
                     onChanged: (e){
                       databaseController.tableList[index]['table_engine']=e;
                     },
                   ),
                 ),
                 SizedBox(height: 5.h,),
                 //Column添加
                 Row(
                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                   children: [
                     CustomText(text: "Column", textStyle: FontConfig.fieldTitle),
                     IconButton(
                       splashColor: Colors.transparent,
                       highlightColor: Colors.transparent,
                       onPressed: (){
                         databaseController.columnList[index].add({
                           "column_id":null,
                           "table_id":0,
                           "column_name":"",
                           "column_type":"",
                           "column_kind":""
                         });
                       },
                       icon: const Icon(Icons.add),
                     ),
                   ],
                 ),
                 //Column列表
                 Obx(()=>Wrap(
                   children: List<Widget>.generate(databaseController.columnList[index].length, (columnIndex){
                     return Container(
                       margin: EdgeInsets.only(bottom: 10.h),
                       padding: EdgeInsets.symmetric(horizontal: 5.w),
                       decoration: BoxDecoration(
                           borderRadius: BorderRadius.circular(10),
                            color: Get.isDarkMode?Colors.white.withOpacity(0.2):Colors.grey.shade100.withOpacity(0.75)
                       ),
                       child: Column(
                         crossAxisAlignment: CrossAxisAlignment.start,
                         children: [
                           Row(
                             children: [
                               SizedBox(
                                 width: 80.w,
                                 child: TextField(
                                   decoration: const InputDecoration(
                                       hintText: "Column",
                                       border: OutlineInputBorder(
                                           borderSide: BorderSide.none
                                       )
                                   ),
                                   onChanged: (e){
                                     databaseController.columnList[index][columnIndex]['column_name']=e;
                                   },
                                 ),
                               ),
                               SizedBox(
                                 width: 80.w,
                                 child: TextField(
                                   decoration: const InputDecoration(
                                       hintText: "Type",
                                       border: OutlineInputBorder(
                                           borderSide: BorderSide.none
                                       )
                                   ),
                                   onChanged: (e){
                                     databaseController.columnList[index][columnIndex]['column_type']=e;
                                   },
                                 ),
                               ),
                               SizedBox(
                                 width: 80.w,
                                 child: TextField(
                                   decoration: const InputDecoration(
                                       hintText: "Kind",
                                       border: OutlineInputBorder(
                                           borderSide: BorderSide.none
                                       )
                                   ),
                                   onChanged: (e){
                                     databaseController.columnList[index][columnIndex]['column_kind']=e;
                                   },
                                 ),
                               ),
                               IconButton(
                                   onPressed: (){
                                     databaseController.columnList[index].removeAt(columnIndex);
                                   },
                                   icon: Icon(Icons.delete_outline)
                               )
                             ],
                           )
                         ],
                       ),
                     );
                   }),
                 ))
               ],
             )
           );
         }),
       ))
      ],
    );
  }

  _appBar(){
    return AppBar(
      title: Text("保存数据库".tr),
      centerTitle: true,
      leading: IconButton(
        onPressed: (){
          Get.offNamed("/Home",arguments: {"selectIndex":3});
        },
        icon: const Icon(Icons.arrow_back),
      ),
    );
  }
}